<template>
  <div class="app-container">
    <el-form 
      :model="queryParams" 
      ref="queryForm" 
      size="small" 
      :inline="true" 
      v-show="showSearch" 
      class="api-search-form">
      <el-card shadow="hover" class="search-card">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="父分类ID">
              <el-input
                v-model="queryParams.parentId"
                placeholder="请输入父分类ID"
                clearable
                prefix-icon="el-icon-search"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分类名称">
              <el-input
                v-model="queryParams.name"
                placeholder="请输入分类名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="显示顺序">
              <el-input-number
                v-model="queryParams.sort"
                placeholder="请输入显示顺序"
                :min="0"
                style="width: 100%"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分类状态">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 100%">
                <el-option label="正常" :value="0"/>
                <el-option label="停用" :value="1"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right;">
            <el-form-item class="search-buttons">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="card-title">API分类列表</span>
        <el-button-group style="float: right;">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['interfaces:interfaceCategory:add']"
          >新增</el-button>
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['interfaces:interfaceCategory:edit']"
          >修改</el-button>
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['interfaces:interfaceCategory:remove']"
          >删除</el-button>
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['interfaces:interfaceCategory:export']"
          >导出</el-button>
        </el-button-group>
      </div>

      <el-table
        v-loading="loading"
        :data="interfaceCategoryList"
        @selection-change="handleSelectionChange"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{background:'#f5f7fa'}"
        highlight-current-row
        row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="分类ID" align="center" prop="id" width="80"/>
        <el-table-column label="父分类ID" align="center" prop="parentId" width="80"/>
        <el-table-column label="分类名称" align="center" prop="name" min-width="150" show-overflow-tooltip/>
        <el-table-column label="显示顺序" align="center" prop="sort" width="100"/>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'" size="mini">
              {{ scope.row.status === 0 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="150" show-overflow-tooltip/>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['interfaces:interfaceCategory:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['interfaces:interfaceCategory:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改API分类对话框 -->
    <el-dialog 
      :title="title" 
      :visible.sync="open" 
      width="600px" 
      append-to-body
      :close-on-click-modal="false"
      :destroy-on-close="true"
      class="api-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="父分类" prop="parentId">
              <el-cascader
                v-model="form.parentId"
                :options="categoryOptions"
                :props="{ checkStrictly: true, value: 'id', label: 'name' }"
                placeholder="请选择父分类"
                clearable
                style="width: 100%">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" controls-position="right" style="width: 100%" placeholder="请输入显示顺序"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitForm" :loading="submitLoading">确 定</el-button>
        <el-button size="small" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInterfaceCategory, getInterfaceCategory, delInterfaceCategory, addInterfaceCategory, updateInterfaceCategory } from "@/api/interfaces/interfaceCategory";

export default {
  name: "InterfaceCategory",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // API分类表格数据
      interfaceCategoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
        name: null,
        sort: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
      },
      // 分类选项
      categoryOptions: [],
      // 提交状态
      submitLoading: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询API分类列表 */
    getList() {
      this.loading = true;
      
      // 创建一个干净的查询对象，避免嵌套参数
      const query = {};
      
      // 处理业务查询参数
      if (this.queryParams.parentId) query.parentId = this.queryParams.parentId;
      if (this.queryParams.name) query.name = this.queryParams.name;
      if (this.queryParams.sort) query.sort = this.queryParams.sort;
      if (this.queryParams.status !== null && this.queryParams.status !== undefined) query.status = this.queryParams.status;
      
      // 直接添加分页参数（不要放在params中嵌套）
      query.pageNum = this.queryParams.pageNum;
      query.pageSize = this.queryParams.pageSize;
      
      console.log('分页请求参数:', query);
      
      // 发送包含分页参数的请求
      listInterfaceCategory(query).then(response => {
        this.interfaceCategoryList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch(error => {
        console.error('获取数据失败:', error);
        this.loading = false;
        this.$message.error('获取数据失败，请刷新页面重试');
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        name: null,
        sort: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加API分类";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInterfaceCategory(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改API分类";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInterfaceCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInterfaceCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除API分类编号为"' + ids + '"的数据项？').then(function() {
        return delInterfaceCategory(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('interfaces/interfaceCategory/export', {
        ...this.queryParams
      }, `interfaceCategory_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
.api-search-form {
  .search-card {
    margin-bottom: 20px;
    ::v-deep .el-card__body {
      padding: 15px 20px 0;
    }
  }
  ::v-deep .el-form-item {
    margin-bottom: 15px;
    .el-form-item__label {
      font-weight: normal;
      color: #606266;
    }
  }
  .search-buttons {
    text-align: right;
    margin-right: 0;
  }
}

.box-card {
  margin-bottom: 20px;
  .card-title {
    font-size: 15px;
    font-weight: bold;
  }
  ::v-deep .el-card__header {
    padding: 10px 20px;
    border-bottom: 1px solid #ebeef5;
  }
}

.api-dialog {
  ::v-deep .el-dialog__body {
    padding: 20px 30px;
    max-height: calc(90vh - 110px);
    overflow-y: auto;
  }
  ::v-deep .el-dialog__header {
    padding: 15px 20px;
    border-bottom: 1px solid #dcdfe6;
    .el-dialog__title {
      font-size: 16px;
      font-weight: bold;
    }
  }
  ::v-deep .el-form-item__label {
    font-weight: 500;
  }
}
</style>
